#include "stdio.h"

#define SCRIPT_FILE_COMMENT         '#'                 // symbol for comment
#define SCRIPT_FILE_END             '%'                 // symbol for file end


// Macro
#define MAX_LINE_SIZE       8000
#define IS_COMMENT(x)       (SCRIPT_FILE_COMMENT == (x))
#define IS_FILE_END(x)      (SCRIPT_FILE_END == (x))
#define IS_LINE_END(x)      ('\r' == (x)|| '\n' == (x))


static char *get_script_next_line(char **line_buf_ptr)
{
    char *line_buf;
    char *next_line;
    int i = 0;

    line_buf = (*line_buf_ptr);

    // strip '\r', '\n' and comment
    while (1)
    {
        // strip '\r' & '\n'
        if (IS_LINE_END(line_buf[0]))
        {
            line_buf++;
        }
        // strip comment
        else if (IS_COMMENT(line_buf[0]))
        {
            for (i = 0; !IS_LINE_END(line_buf[0]) && i <= MAX_LINE_SIZE; i++)
            {
                line_buf++;
            }

            if (i > MAX_LINE_SIZE)
            {
                line_buf[0] = SCRIPT_FILE_END;

                printf ("Error: the max size of one line is %d!!!\n", MAX_LINE_SIZE); // <-@@@

                break;
            }
        }
        else
        {
            break;
        }
    }

    // get next line
    if (IS_FILE_END(line_buf[0]))
    {
        next_line = NULL;
    }
    else
    {
        next_line = line_buf;

        for (i = 0; !IS_LINE_END(line_buf[0]) && i <= MAX_LINE_SIZE; i++)
        {
            line_buf++;
        }

        if (i > MAX_LINE_SIZE)
        {
            next_line = NULL;

            printf ("Error: the max size of one line is %d!!!\n", MAX_LINE_SIZE); // <-@@@
        }
        else
        {
            line_buf[0] = '\0';
            *line_buf_ptr = line_buf + 1;
        }
    }

    return next_line;
}

int script_test(const char* fileName)
{
    char* file_buffer = malloc(MAX_LINE_SIZE);
    char* script_buf =file_buffer;


    char* next_line=NULL;
    FILE *fp =fopen(fileName,"r");
    if(!fp){
        return -1;
    }

    fread(script_buf,1,4096,fp);
    while ((next_line = get_script_next_line(&script_buf)) != NULL)
    {
        printf("cmd:%s\n",next_line);
    }





    if(file_buffer){
        free(file_buffer);
    }
    
    return 0;

failed_malloc:
    if(fp){
        fclose(fp);
    }
    return -1;

}
int main(int argc,char *argv[])
{
    if(argc>1){
        return script_test(argv[1]);
    }
    return 0;
}
    